package com.thd.springboottest.sso.client.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thd.springboottest.sso.vo.AuthBean;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * com.thd.springboottest.sso.client.service.SessionIdUtil
 *
 * @author: wanglei62
 * @DATE: 2021/8/22 14:46
 **/
public class SessionIdUtil {
    public static AuthBean checkSsoToken(String ssoToken){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8899/ssoserver/checkSsoToken/" + ssoToken);

        CloseableHttpResponse res = null;
        try {
            res = httpClient.execute(httpGet);

            HttpEntity httpEntity = res.getEntity();
            if (httpEntity != null) {
                System.out.println("长度：\t" + httpEntity.getContentLength());


                String responseStr = EntityUtils.toString(httpEntity,"UTF-8");
                System.out.println("内容：\t" + responseStr);
                ObjectMapper objectMapper = new ObjectMapper();
                AuthBean auth = objectMapper.readValue(responseStr,AuthBean.class);

                return auth;
            }
            return null;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 先从cookie中获取sessoinid如果没有则从url的参数中获取sessionid  均忽略大小写
     * @param servletRequest
     * @return
     */
    public static String getSessionId(ServletRequest servletRequest){
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        Cookie[] cookies = request.getCookies();
        String sessionId = null;
        if(null != cookies){
            Optional<Cookie> cookieOptional = Stream.of(cookies).filter(item -> "sessionid".equalsIgnoreCase(item.getName())).findFirst();
            if(cookieOptional.isPresent()){
                sessionId = cookieOptional.get().getValue();
                return sessionId;
            }
        }

        Enumeration<String> params = servletRequest.getParameterNames();
        if(params.hasMoreElements()){
            String paramName = params.nextElement();
            if("sessionid".equalsIgnoreCase(paramName)){
                return servletRequest.getParameter(paramName);
            }
        }
        return null;


    }

    public static void setSessionId(ServletResponse response,String sessionId){
        Cookie ck = new Cookie("sessionId",sessionId);
        ck.setPath("/");
        ck.setMaxAge(24 * 60 * 60);
        HttpServletResponse res = (HttpServletResponse)response;
        res.addCookie(ck);
    }

    public void clearSessionId(ServletResponse response){
        Cookie ck = new Cookie("sessionId",null);
        ck.setPath("/");
        ck.setMaxAge(0);
        HttpServletResponse res = (HttpServletResponse)response;
        res.addCookie(ck);
    }
}
